package com.example.lenovo.sendshortmsg;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/10/16.
 */

public class ContactActivity extends AppCompatActivity {
    private ArrayList<Contact> contacts = new ArrayList<>();
    private ListView lv_contact;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact);

        lv_contact = (ListView) findViewById(R.id.lv_contact);
        for(int i = 0 ; i < 20 ; i++) {
            Contact contact = new Contact();
            contact.name = "张三" + i;
            contact.phone = "13888888" + i;
            contacts.add(contact);
        }
        lv_contact.setAdapter(new MyAdapter());
        //  给listView设置item监听事件
        lv_contact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //  ①获取到电话
                Contact contact = contacts.get(position);

                Intent data = new Intent();
                data.putExtra("phone",contact.phone);
                setResult(2,data);  //  把数据封装到intent中传递回来  ============第三步====================

                //  当开启的Activity关闭之后，会走到上一层的onActivityResult方法（重写）
                //   finish    ->    onActivityResult    ->  startActivityResult
                finish();   //      ======================第四步========================
            }
        });
    }
    private class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return contacts.size();
        }

        @Override
        public Object getItem(int i) {
            return contacts.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            View view  = null;
            if (convertView == null)
                view = View.inflate(getApplicationContext(),R.layout.item_contact,null);
            else
                view = convertView;

            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            TextView tv_phone = (TextView)view.findViewById(R.id.tv_phone);
            Contact c = contacts.get(position);
            if (c != null) {
                tv_name.setText(c.name);
                tv_phone.setText(c.phone);
            }
            return view;
        }
    }
}
